package com.codingman.springmvcdemo6.crud;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.view.RedirectView;

@Controller
public class EmployeeController {
	@Autowired
	EmployeeDao employeeDao;

	@ModelAttribute("sexs")
	public Map<String, String> getSexList() {
		Map<String, String> sexList = new HashMap<String, String>();
		sexList.put("F", "Female");
		sexList.put("M", "Male");
		return sexList;
	}

	@ModelAttribute("countries")
	public List<String> getCountryList() {
		List<String> countryList = new ArrayList<String>();
		countryList.add("USA");
		countryList.add("China");
		countryList.add("England");
		return countryList;
	}

	@RequestMapping("/addform")
	public String addForm(Model model) {
		Employee emp = new Employee();
		model.addAttribute("employee", emp);
		return "add";
	}

	@RequestMapping("/listform")
	public String listForm(Model model) {
		List<Employee> list = employeeDao.getAllEmployees();
		model.addAttribute("employees", list);
		return "list";
	}

	@RequestMapping("/editform/{id}")
	public String editForm(@PathVariable int id, Model model) {
		Employee emp = employeeDao.getEmployeeById(id);
		model.addAttribute("employee", emp);
		return "edit";
	}

	@RequestMapping("/addemp")
	public String save(@ModelAttribute("employee") Employee emp) {
		employeeDao.save(emp);
		return "redirect:listform";
	}

	@RequestMapping("/editemp")
	public String update(@ModelAttribute("employee") Employee emp) {
		employeeDao.update(emp);
		return "redirect:listform";
	}

	@RequestMapping("/deleteemp/{id}")
	public String delete(@PathVariable int id, Model model) {
		employeeDao.delete(id);
		return "redirect:listform";
	}

	@RequestMapping("/")
	public String index() {
		return "index";
	}
}
